package com.example.mybrowser;

import java.io.IOException;
import java.security.PublicKey;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpException;

import com.example.mybrowser.WebsiteInfo.Information;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class MainActivity extends ActionBarActivity {

	public static String TIME_CHANGED_ACTION = "com.zyg.demo.service.dynamicui.action.TIME_CHANGED_ACTION";  
    public static TextView time = null;  
    private Intent timeService = null; 
    
	static String serverIP = "162.105.51.189";
	static int serverPort = 8080;
	MobileService mobileService;
	MobileHandler mobileHandler;
	ResourceSocketThread[] resthread;
	MobileCache mobileCache;
	MyHandler myHandler; 
	String Android_ID;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Android_ID = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		WebView myWebView = (WebView)findViewById(R.id.webview);
		myWebView.setWebViewClient(new WebViewClientDemo());
		//getActionBar().setDisplayHomeAsUpEnabled(true);
		SharedPreferences setinfo = getPreferences(Activity.MODE_PRIVATE);
		WebsiteInfo info = new WebsiteInfo();
		info.initRSS(setinfo);
		
		//ÉèÖÃ¶¨Ê±µÄ²Ù×÷
		time = (TextView)findViewById(R.id.mytime);
		registerBroadcastReceiver();
		startTimeService(); 
		
		
		myWebView.getSettings().setJavaScriptEnabled(true);
		myWebView.getSettings().setAppCacheEnabled(false);

		/*myWebView.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				WebView wb = (WebView) findViewById(R.id.webview);
				String Url = wb.getUrl();
				EditText et = (EditText) findViewById(R.id.edit_message);
				et.setText(Url);
				et.setFocusable(false);
				wb.requestFocus();
				return false;
			}
			
		});*/
		myWebView.getSettings().setJavaScriptEnabled(true);

		myHandler = new MyHandler(this);
		
		mobileCache = new MobileCache(getFilesDir().getAbsolutePath(), getAssets());		
		//mobileCache = new MobileCache(Environment.getExternalStorageDirectory()+"/SmartBrowser", getAssets());
		PrefetchConn.Android_ID = Android_ID;
		PrefetchConn.mobileCache = mobileCache;
		
		ProxySetting.setProxy(myWebView, "localhost", 8080, "");
		
		resthread = new ResourceSocketThread[1000];
		
		mobileService = new MobileService(resthread, mobileCache, this, myHandler, Android_ID);
		mobileService.start();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // Inflate the menu items for use in the action bar
		super.onCreateOptionsMenu(menu); 
		MenuItem home = menu.add(0,0,0,"home_button");  
        MenuItem refresh = menu.add(0,0,0,"fresh"); 
        MenuItem rss = menu.add(0,0,0,"rss");
        home.setIcon(R.drawable.home_button);
        refresh.setIcon(R.drawable.refresh);
        rss.setIcon(R.drawable.rss);
        
        //°ó¶¨µ½ActionBar    
        home.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  
        refresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);   
        rss.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		CharSequence title = item.getTitle();
		if (title == "home_button") {
			loadHomePage();
			return true;
		}
		else if (title == "fresh")
		{
			WebView wb = (WebView)findViewById(R.id.webview);
			wb.reload();
			return true;
		}
		else if (title == "rss")
		{
			Intent intent = new Intent(this, SubActivity.class);
			startActivity(intent);
			return true;
		}
		else
		{
			
			WebView wb = (WebView)findViewById(R.id.webview);
			EditText et = (EditText)findViewById(R.id.edit_message);
			if (wb.canGoBack())
				wb.goBack();
			else
				loadHomePage();
			return true;
		}
		//return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}
	
	public void sendMessage(View view) {
	    // Do something in response to button
		loadWebPage();
	}
	
	private class WebViewClientDemo extends WebViewClient {
		@Override
		// 在WebView中而不是默认浏览器中显示页面
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
		    view.loadUrl(url);
		    return true;
		}
		
		@Override
		public void onPageFinished(WebView view, String url)
		{
			WebView wb = (WebView) findViewById(R.id.webview);
			String Url = wb.getUrl();
			EditText et = (EditText) findViewById(R.id.edit_message);
			et.setText(Url);
		}
	}
	
	private void loadWebPage()
	{
		WebView myWebView = (WebView) findViewById(R.id.webview);
	    EditText editText = (EditText) findViewById(R.id.edit_message);
	    String message = editText.getText().toString();
	    FragmentManager fragmentManager = getFragmentManager();
    	FragmentTransaction ft = fragmentManager.beginTransaction();
    	android.app.Fragment table = fragmentManager.findFragmentById(R.id.table);
    	android.app.Fragment viewer = fragmentManager.findFragmentById(R.id.viewer);
    	ft.hide(table);
    	// Commit the transaction
    	if (!viewer.isVisible())
    	{
    		ft.show(viewer);   		
    	}
    	ft.commit();
    	message = editURL(message);
	    myWebView.loadUrl(message);
	}
	
	private void loadHomePage()
	{
		EditText editText = (EditText) findViewById(R.id.edit_message);
		editText.setText("");
		FragmentManager fragmentManager = getFragmentManager();
    	FragmentTransaction ft = fragmentManager.beginTransaction();
    	android.app.Fragment table = fragmentManager.findFragmentById(R.id.table);
    	android.app.Fragment viewer = fragmentManager.findFragmentById(R.id.viewer);
    	ft.hide(viewer);
    	// Commit the transaction 	
    	if (!table.isVisible())
    	{
    		ft.show(table);
    	}
    	ft.commit();
	}
	
	private String editURL(String message)
	{
		String pre = message.substring(0, 10);
		pre = pre.toLowerCase();
		if (pre.startsWith("http://"))
			return message;
		else
		{
			message = "http://" + message;
			return message;
		}
	}
	
	
	@Override
	public void onStart(){
		super.onStart();
		final EditText et = (EditText)findViewById(R.id.edit_message);
		int amount = 0;
    	int images[] = {R.id.image1, R.id.image2, R.id.image3, R.id.image4,R.id.image5, R.id.image6};
    	final Map<Integer, Information> RSS = WebsiteInfo.RSSInfo;
		for (int i = 0; i < 3; i++) {
            if (RSS.containsKey(i))
            {
            	ImageView pic = (ImageView)findViewById(images[amount]);
            	amount++;
            	int pic_id = RSS.get(i).image;
        		pic.setBackgroundResource(pic_id);
        		if (i == 0){
        			pic.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        	et.setText("http://xw.qq.com/simple/s/index/");
                        	loadWebPage();
                        }
            		});
        		}
        		else if (i == 1)
        		{
        			pic.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        	et.setText("http://i.ifeng.com/?vt=2");
                        	loadWebPage();
                        }
            		});
        		}
        		else
        		{
        			pic.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        	et.setText("http://3g.163.com/x/");
                        	loadWebPage();
                        }
            		});
        		}
            }
        }
		for (int i = amount; i < 3; i++)
		{
			ImageView pic = (ImageView)findViewById(images[i]);
			pic.setBackgroundColor(0xffffff);
			pic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                	et.setText("");
                }
    		});
		}
	}
	
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		//Í£Ö¹·þÎñ  
        stopService(timeService);  
		SharedPreferences perference = getPreferences(Activity.MODE_PRIVATE); 
        Editor editor = perference.edit(); 
        Map<Integer, Information> RSS = WebsiteInfo.RSSInfo;
        Iterator iter = RSS.entrySet().iterator();
        int amount = 0;
        while (iter.hasNext()) {
        	Map.Entry entry = (Map.Entry) iter.next();
        	int key = (Integer) entry.getKey();
        	editor.putInt(String.valueOf(amount), key);
        	amount++;
        }
        for (int i = amount; i < 3; i++)
        {
        	editor.putInt(String.valueOf(i), -1);
        }
        editor.commit();
	} 
	
	private void registerBroadcastReceiver(){  
        UITimeReceiver receiver = new UITimeReceiver();  
        IntentFilter filter = new IntentFilter(TIME_CHANGED_ACTION);  
        registerReceiver(receiver, filter);  
    } 
	
	private void startTimeService(){  
        timeService = new Intent(this,TimeService.class);  
        this.startService(timeService);  
    }  

    /*5.14*/
    public void getontime(){
    	new Thread()
    	{
    		public void run()
    		{
				try
				{
					PrefetchConn.getPrefetch();
				}
				catch (HttpException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	}.start();
    }
}
